<?php
//checkout.php
session_start();
include_once("config/config.inc.php");
include_once("config/lobby.inc.php");
include_once("reporting.php");
include_once("class.room.php");
include_once("paymentpad.php");
include_once("currentcash.function.php");


function getRoomMinibarQty($room,$mb)
{
	$sql = "select qty from room_minibar where room_id='$room' and minibar_id='$mb' ";
	$res = mysql_query($sql) or die($sql);

	$num = mysql_num_rows($res);
	if($num) {
		$row = mysql_fetch_row($res);
		return $row[0];
	}else{
		return 0;
	}
}

$room =($_GET["roomid"]) ? $_GET["roomid"] : $_POST["roomid"];

$user = $_SESSION["hotel"]["userid"];

if($_POST["act"]=='paybalance') { //process payment
	$cash = $_POST["newcash"];
	$card = $_POST["newcard"];
	$change = $_POST["newchange"] * (-1);
	$occupancy=$_POST["occupancy"];
	$roomid=$_POST["roomid"];
	$user = $_SESSION["hotel"]["userid"];
	$amountdue = $_POST["new_balance"];
	$now = date("Y-m-d H:i:s");
	//if there are adjustments, add the adjustments 
	
	//ot additional costs:
	$ot_amount=$_POST["hiddenotamount"];
	$ot_hours=$_POST["hiddenothours"];
	
	if($ot_hours >= 1) {
		//die("pumasok");
		//insert entries as room sales
		$total_ot = $ot_amount * $ot_hours;
		$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id , unit_cost, qty, status,update_date,update_by) 
			values ('$occupancy', '$now', 3, 16,'$ot_amount','$ot_hours','Paid','$now','$user') ";
		
   		mysql_query($sql);
		//update occupancy to record extension
		$sql = "update occupancy set expected_checkout='$now' where occupancy_id='$occupancy'";
		mysql_query($sql) or die(mysql_error());

		//update occupancy_log to record extension
		$sql = " insert into occupancy_log(transaction_date, occupancy_id, update_by, remarks, transaction_type )
		value ('$now', '$occupancy', '$user', 'Overtime on checkout', 'Extension' ) ";
		mysql_query($sql) or die($sql);
	}

	/*
	//adjustments
	$adjustment = $_POST["new_adjustment"];
	$remark = $_POST["new_remark"];
	$oic = $_POST["new_adj_oic"];
	if($adjustment) {
		//insert into room_sales
		$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id ,  unit_cost, qty) 
			values ('$occupancy', '$now', 3,18,'$adjustment','1') ";
		mysql_query($sql);
	}
	*/

	//receipts
	if($cash) {		
		$tender = $cash+$change;
		
		$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,update_by) 
			values ('$now', '$occupancy', 'Cash', '$tender','$user')";
		mysql_query($sql) or die($sql . mysql_error());

		setCurrentCash($tender,'in',$user);
	}
	if($card) {
		$approve=$_POST["newapprove"];
		$batch=$_POST["newbatch"];
		$cardtype = $_POST["ctype"];
		$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,update_by) 
			values ('$now', '$occupancy', 'Card', '$card','$user')";
		mysql_query($sql) or die($sql . mysql_error());
		//insert card details
		$newsalesid = mysql_insert_id();
		$sql = " insert into card_payment_details (salesreceipt_id, card_type, approval_code, batch_number) 
				values ('$newsalesid','$cardtype','$approve','$batch')";
		mysql_query($sql) or die($sql . mysql_error());
	}
	$totaltender = $cash+$card;
	
	if(isset($_POST['fnb_cb']) && is_array($_POST['fnb_cb'])) {
		$list  = implode(',',$_POST['fnb_cb']);
		$sql =" update fnb_sales set status='Paid',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where fnbsales_id in ($list) and occupancy_id='$occupancy' and status in ('Printed','Draft')";
		mysql_query($sql) or die(mysql_error());	
	}
	if(isset($_POST['misc_cb']) && is_array($_POST['misc_cb'])) {
		$list  = implode(',',$_POST['misc_cb']);
		$sql =" update room_sales set status='Paid',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where roomsales_id in ($list) and occupancy_id='$occupancy' and status in ('Printed','Draft')";
		mysql_query($sql) or die(mysql_error());	
	}
	if(isset($_POST['room_cb']) && is_array($_POST['room_cb'])) {
		$list  = implode(',',$_POST['room_cb']);
		$sql =" update room_sales set status='Paid',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where roomsales_id in ($list) and occupancy_id='$occupancy' and status in ('Printed','Draft')";
		
		mysql_query($sql) or die(mysql_error());	
	}
	
	if($totaltender >= $amountdue) {
		$sql = "select fnbsales_id from fnb_sales where occupancy_id = '$occupancy' and order_code ='".$occupancy."17132' and status in ('Printed')";
		$res = mysql_query($sql);
		$num = mysql_num_rows($res);
		if($num>0)
		{
			//Replenish Mini Ref
			$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
			$obj3 = new Reporting($room);
			$retval.=$obj3->printablefosreplenish(1,$occupancy."17132")."\n\n\n\n\n";
			$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);
			$file = "fos{$roomid}.txt";
			$fp = fopen("reports/" .$file, "w");
			fwrite($fp,$retval);
			fclose($fp);
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);
			shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p_kitchen.bat ' . $file);
		}
		
		/*
		$sql =" update room_sales set status='Paid',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where occupancy_id='$occupancy' and status in ('Printed','Draft')";
		mysql_query($sql) or die(mysql_error());
		$sql =" update fnb_sales set status='Paid',update_by='$user',update_date = '".date("Y-m-d H:i:s")."' where occupancy_id='$occupancy'  and status in ('Printed')";
		mysql_query($sql) or die(mysql_error());
		*/
	}
	header("location: checkout.php?roomid=$roomid");
}elseif($_POST["act"]=='deposit'){
	$cash = $_POST["newcash"];
	$card = $_POST["newcard"];
	$change = $_POST["newchange"] * (-1);
	$occupancy=$_POST["occupancy"];
	$roomid=$_POST["roomid"];
	$user = $_SESSION["hotel"]["userid"];
	$now = date("Y-m-d H:i:s");
	if($cash) {
		$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,update_by) 
			values ('$now', '$occupancy', 'Cash', '$cash','$user')";
		mysql_query($sql) or die($sql . mysql_error());
		setCurrentCash($cash,'in',$user);
	}
}elseif($_POST["act"]=='checkout'){
	$norefund = $_POST['norefundflag'];
	$occupancy=$_POST["occupancy"];
	$room = $_POST["roomid"];
	$user = $_SESSION["hotel"]["userid"];
	if($norefund==1) {
		//get current sales_date for  occupancyid
		$now = date('Y-m-d H:i:s');
		$sql = "select roomsales_id, sales_date from room_sales where occupancy_id='$occupancy' 
				and sales_date < '$now' order by sales_date desc";
		$res = mysql_query($sql);
		list($roomsales_id, $lastdate)=mysql_fetch_row($res);
		$sql = "update room_sales set sales_date='$lastdate',remarks='Early Checkout'
				where status='Paid' and occupancy_id='$occupancy' and roomsales_id > $roomsales_id";
		mysql_query($sql);
		
	}
	//update occupancy
	$now = date("Y-m-d H:i:s");
	$obj2 = new Reporting($room);
	//print checkout SOA
	$retval=chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
	$retval.=$obj2->printableCheckoutsoa()."\n\n\n\n\n";
	$retval.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);	
	$file = "soa{$room}.txt";
	$fp = fopen("reports/" .$file, "w");
	fwrite( $fp,$retval);
	fclose($fp);
	shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);


	$sql = "update occupancy set actual_checkout='$now', update_by='$user' where occupancy_id='$occupancy'";	
	mysql_query($sql) or die($sql . mysql_error());
	
	//add occupancy log
	$sql = " insert into occupancy_log(transaction_date, occupancy_id, update_by, remarks ) value ('$now', '$occupancy', '$user', 'CheckOut' ) ";
	mysql_query($sql) or die($sql . mysql_error());
	
	//update room status
	$sql = " update rooms set status=3, last_update='$now',update_by='$user' where room_id='$room' ";
	mysql_query($sql) or die($sql . mysql_error());
	$rm = new room($room);
	$f=$rm->floor_id - 1;

	echo "<script language='javascript'>parent.document.location.href='../index.php?f=$f&room=$room'</script>";
	exit;
}elseif($_POST["act"]=="addjust"){
	$adjustment = $_POST["new_adjustment"];
	$remark = $_POST["new_remark"];
	$occupancy = $_POST["occupancy"];
	$now = date("Y-m-d H:i:s");
	
	switch($_POST['newsalestype']) {
		case 'room':
			$title='Room Adjustment';
			$table='room_sales';
			$category=3;
			$item=18;
			break;
		case 'misc':
			$title='Miscellaneous Adjustment';
			$table='room_sales';
			$category=1;
			$item=29;
			break;
		case 'food':
			$title='Food Adjustment';
			$table='fnb_sales';
			$category=22;
			$item=114;
			break;
		case 'beer':
			$title='Beer Adjustment';
			$table='fnb_sales';
			$category=21;
			$item=113;
			break;
	}
	if($adjustment!='' && $table!='' && $category!='' && $item!='') {
		
		//insert into room_sales
		$sql  =" insert into $table( occupancy_id, sales_date, category_id, item_id ,  unit_cost, qty, remarks,update_date,update_by,status) 
			values ('$occupancy', '$now', '$category','$item','$adjustment','1','$remark','".date("Y-m-d H:i:s")."','$user','Paid') ";
		mysql_query($sql) or die($sql.' '.mysql_error());
		
		//print adjustment
		$sql2 = "select room_id from occupancy where occupancy_id='$occupancy' ";
		$res2 = mysql_query($sql2);
		list($room)=mysql_fetch_row($res2);
		$report = new Reporting($room);
		$print =chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
		$print .= $report->printableheader($title);
		$print .= "\n$remark\t\t $adjustment ";
		$print .= chr(hexdec('1D')).chr(hexdec('56')).chr(49);	
		$file = "adjust{$room}.txt";
		$fp = fopen("reports/$file" , "w") or die('could not open file');
		fwrite( $fp,$print);
		fclose($fp);
		shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);
	}
	exit;
}elseif($_POST["act"]=="cancel"){
	$adjustment = $_POST["new_adjustment"];
	$remark = $_POST["new_remark"];
	$occupancy = $_POST["occupancy"];
	$now = date("Y-m-d H:i:s");
	switch($_POST['newsalestype']) {
		case 'room':
			$title="Room Cancellation";
			$table='room_sales';
			$category=3;
			$item=18;
			break;
		case 'misc':
			$title="Miscellaneous Cancellation";
			$table='room_sales';
			$category=1;
			$item=29;
			break;
		case 'food':
			$title="Food Cancellation";
			$table='fnb_sales';
			$category=22;
			$item=114;
			break;
		case 'beer':
			$title="Beer Cancellation";
			$table='fnb_sales';
			$category=21;
			$item=113;
			break;
	}
	if($adjustment) {
		//insert into room_sales
		$sql  =" insert into $table( occupancy_id, sales_date, category_id, item_id ,  unit_cost, qty, remarks,update_date,update_by,status) 
			values ('$occupancy', '$now', '$category','$item','-$adjustment','1','$remark','".date("Y-m-d H:i:s")."','$user','Paid') ";
		mysql_query($sql) or die($sql.' '.mysql_error());
		
		//print adjustment
		$sql = "select room_id from occupancy where occupancy_id='$occupancy' ";
		$res = mysql_query($sql);
		list($room)=mysql_fetch_row($res);		
		$report = new Reporting($room);
		$print =chr(hexdec('1B')).chr(hexdec('4D')).chr(1);
		$print .= $report->printableheader($title);
		$print .="\n $remark \t\t -$adjustment";
		$print.=chr(hexdec('1D')).chr(hexdec('56')).chr(49);	
		$file = "cancel{$room}.txt";
		$fp = fopen("reports/" .$file, "w");
		fwrite( $fp,$print);
		fclose($fp);
		shell_exec('c:\pstools\psexec c:\xampp\htdocs\fds\ajax\p.bat ' . $file);
	}
	exit;
}elseif($_POST["act"]=="security"){
	$now = date("Y-m-d H:i:s");
	$security_type=$_POST["receivable_type"];
	$occupancy=$_POST["occupancy"];
	$room = $_POST["roomid"];
	$user = $_SESSION["hotel"]["userid"];
	$cashval= $_POST["new_cashvalue"];
	$fname= $_POST["new_firstname"];
	$lname= $_POST["new_lastname"];
	$remarks= $_POST["new_remark"];
	$oic= $_POST["new_adj_oic2"];
	if(isset($cashval) && isset($fname) && isset($remarks)) {
		$sql = " insert into salesreceipts(receipt_date, occupancy_id, tendertype, amount,update_by) 
				values ('$now', '$occupancy', 'Security', '$cashval','$user')";
		mysql_query($sql) or die($sql . mysql_error());
		$receiptid=mysql_insert_id();
		$sql = " insert into security_receivables (date_endorsed, amount, remarks, oic, guest_fname,guest_lname) 
				values ('$now','$cashval','$security_type [  $receiptid  ]: $remarks','$oic','$fname','$lname') ";
		mysql_query($sql) or die($sql . mysql_error());

		//update basic room rates

		$sql =" update room_sales set status='Paid',update_by='$user', update_date = '".$now."' where occupancy_id='$occupancy' and status in ('Printed','Draft')";
		mysql_query($sql) or die(mysql_error());
		$sql =" update fnb_sales set status='Paid',update_by='$user', update_date = '".$now."' where occupancy_id='$occupancy'  and status in ('Printed')";
		mysql_query($sql) or die(mysql_error());

	
		//if ot on checkout, compute and account for ot costs/sales
		$ot_amount=$_POST["hiddenotamount"];
		$ot_hours=$_POST["hiddenothours"];
		
		if($ot_hours >= 1) {
			//die("pumasok");
			//insert entries as room sales
			$total_ot = $ot_amount * $ot_hours;
			$sql  =" insert into room_sales( occupancy_id, sales_date, category_id, item_id , unit_cost, qty, status,update_date,update_by) 
				values ('$occupancy', '$now', 3, 16,'$ot_amount','$ot_hours','Paid','".$now."','$user') ";
			
			mysql_query($sql);
			//update occupancy to record extension
			$sql = "update occupancy set expected_checkout='$now' where occupancy_id='$occupancy'";
			mysql_query($sql) or die(mysql_error());

			//update occupancy_log to record extension
			$sql = " insert into occupancy_log(transaction_date, occupancy_id, update_by, remarks, transaction_type )		
			value ('$now', '$occupancy', '$user', 'Overtime on checkout', 'Extension' ) ";
			mysql_query($sql) or die($sql);
		}

		echo "success";
		exit;
		//header("location: checkout.php?roomid=$room");
	}else{
		$recErrMesg='Please enter a valid First name, cash value and remarks.';
		echo "fail";
		exit;
		//header("location: checkout.php?roomid=$room&recerr=$recErrMesg");
	}
	
}elseif($_POST["act"]=="oicappr"){
	$user = $_POST["usr"];
	$pwd = $_POST["pwd"];
	$sql = " select user_id from users where username='$user' 
			and userpass='$pwd'  ";
	$res = mysql_query($sql) or die($sql);
	if(mysql_num_rows($res)) {
		list($uid)=mysql_fetch_row($res);
		echo $uid ;
	}else{
		echo 0;
	}
	exit;
}elseif($_POST['act']=='addminibar'){	
	
	$fnbid=$_POST["minibar_item"];
	$count = $_POST["minibar_item_count"];
	if($count) {
		$sql ="select food_category_id, fnb_price from fnb where fnb_id='$fnbid'";
		$res = mysql_query($sql);
		list($fid, $price)=mysql_fetch_row($res);
		$occupancy=$_POST["occupancy"];
		//echo "$fnbid->$count, cat $fid, $price , occ $occupancy";
		$now = date("Y-m-d H:i:s");
		$stamp = $occupancy."17132";
		$isql = "insert into fnb_sales(sales_date, order_code, occupancy_id, category_id, item_id, unit_cost, qty, status, remarks,update_by)
			values('$now', '$stamp','$occupancy','$fid','$fnbid','$price','$count','Printed','Minibar Item','$user');
		";
		mysql_query($isql);
	}
	header("location:checkout.php?roomid=$room");
}



$obj = new Reporting($room);
$rm = new Room($room);
$obj->occupancy;
?>
<link rel="stylesheet" type="text/css" href="../css/ajaxphp.css" />
<link rel="stylesheet" type="text/css" href="../css/jquery.keypad.css" />
<style>
#balancetable, #adjustmenttable,#securitytable {font-size:.7em; width:100%}
.adjustelement {width:100%;background-color:#ffeedd;}
#new_adjustment {text-align:right;}
#cmdApprove, #cmdFingerScan,#cmdApprove2, #cmdFingerScan2{background-color:#FFCC66;
	padding:2px;}
.balance {
	border:0px;font-size:12px;
	font-weight:bold;color:#ff0000;
	background-color:#ffffff;
	border-top:1px dotted #111111;
	text-align:right;
}
.error {
	border:1px solid #ff0000;
	background-color: #ffaaaa;
	color:#000000;
}

</style>
<script type='text/javascript' src='../js/jquery.js'></script>
<script type='text/javascript' src='../js/jquery.keypad.pack.js'></script>
<script lang="javascript">
var focusme="newcash";
function recompute() {
	var totbal = $("#hiddentotal").val() *1;
	var change = $("#newchange").val() *1;
	var cash  = $("#newcash").val()*1;
	var card  = $("#newcard").val()*1;
	var adj = $("#new_adjustment").val()*1;
	var newtotal = totbal + adj;
	var tender = cash + card;
	change =  tender - newtotal;
	$("#newchange").val(change.toFixed(2));
	$("#new_balance").val(newtotal.toFixed(2));
	if($("#new_balance").val() > 0) {
		$("#cmdCheckout").hide();
		$("#receiptflagdiv").hide();
		//$("#cmdPrintSOA").hide();
		$("#cmdDeposit").show();
		$("#cmdPay").show();
	}else if($("#new_balance").val() < 0) {
		$("#cmdCheckout").hide();
		$("#receiptflagdiv").hide();
		//$("#cmdPrintSOA").hide();
		$("#cmdDeposit").show();
		//$("#cmdPay").show().val("Return Balance");
		$("#cmdPay").show();
	}else{
		$("#cmdDeposit").show();
		$("#cmdPay").show();
	}
}
var myinterval='';
$(document).ready(function(){
		$('#newapproval').keypad({keypadOnly: false, 
    layout: $.keypad.qwertyLayout});
		$('#newbatch').keypad({keypadOnly: false, 
    layout: $.keypad.qwertyLayout});
		$("#divAdjustment").show();
		$('#divAdjustment :input').removeAttr('disabled');
		$("#divCancel").hide();
		$('#divCancel :input').attr('disabled', true);
		$("#cmdAccept").hide();
		$("#new_adjustment").keypad();
		$("#cmdApprove").click(function(){
			var rbl = $("input[@name='rbltype']:checked").val()
			if(rbl=="Adjustment")
			{
				$.post("checkout.php",{act:'oicappr', usr: $("#new_adj_oic").val(), pwd:$("#new_adj_pwd").val() },function(resp){
					if(resp > 0) {
						//recompute();
						//$("#cmdAccept").show();
						$.post("checkout.php",{
							act			:'addjust', 
							occupancy	: $("#occupancy").val(),
							new_remark	:$("#new_remark_4").val(), 
							new_adjustment:$("#new_adjustment").val(),
							newsalestype: $("#newsalestype").val()
							});
						window.location.reload(true);
					}else{
						alert("Invalid OIC credentials.");
					}					
				});
				
			}
			else
			{
				$.post("checkout.php",{act:'oicappr', usr: $("#new_adj_oic").val(), pwd:$("#new_adj_pwd").val() },function(resp){
					if(resp > 0) {
						//recompute();
						//$("#cmdAccept").show();
						$.post("checkout.php",{
							act:'cancel', 
							occupancy: $("#occupancy").val(),
							new_remark:$("#new_remark_2").val(), 
							new_adjustment:$("#new_adjustment").val(),
							newsalestype: $("#newsalestype").val()
							});
						window.location.reload(true);
					}else{
						alert("Invalid OIC credentials.");
					}
				});
			}
			
		});

		$("#cmdApprove2").click(function(){
			$.post("checkout.php",
				{act:'oicappr', usr: $("#new_adj_oic2").val(), pwd:$("#new_adj_pwd2").val() },
				function(resp){
					if(resp > 0) {
						$.post("checkout.php",{
							act:'security', 
							roomid: $('#roomid').val(),
							occupancy: $("#occupancy").val(),
							receivable_type: $("#receivable_type").val(),
							new_remark:$("#recvbl_remarks").val(),
							new_firstname:$("#recvbl_firstname").val(),
							new_lastname:$("#recvbl_lastname").val(),
							receivable_type:$("#receivable_type").val(),
							new_adj_oic2:$("#new_adj_oic2").val(),
							hiddenotamount:$("#hiddenotamount").val(),
							hiddenothours:$("#hiddenothours").val(),
							new_cashvalue:$("#recvbl_cashvalue").val() }
							,function(res) {
								if(res == 'success') {
									window.location.reload(true);
								}else{
									$("div.error").html("Please fill in required fields.");
								}
							}
							);
							//
					}else{
						alert("Invalid OIC credentials.");
					}
			});
			return false;
		});

		$("#rbltype_1").click(function(){			
			//var rbl = $("input[@name='rbltype']:checked").val();			
			$("#divAdjustment").show();
			$('#divAdjustment :input').removeAttr('disabled');
			$("#divCancel").hide();
			$('#divCancel :input').attr('disabled', true);		
		});

		$("#rbltype_2").click(function(){	
			//var rbl = $("input[@name='rbltype']:checked").val();			
			$("#divCancel").show();
			$('#divCancel :input').removeAttr('disabled');
			$("#divAdjustment").hide();
			$('#divAdjustment :input').attr('disabled', true);
		});

		$(".tender").click(function(){
			$(".tender").removeClass("hilite");
			focusme = $(this).attr("id");
			$(this).addClass("hilite");
		});
		$(".denomination").click(function() {
			if($(this).val()=="Clear") {
				$("#" + focusme).val( 0);	
			}else{
				var curval = $("#" + focusme).val() * 1;
				var newval = $(this).val() * 1;
				$("#" + focusme).val( curval + newval);
			}
			if($("#newcard").val()==0) $("#carddetails").hide();
			else $("#carddetails").show();
			recompute();
		});
		recompute();
		$("#cmdPay").click(function(){
			var msg = '\nCash:' + $('#newcash').val();
			msg += '\nCard:' + $('#newcard').val();
			if(confirm('Confirm transaction:\n' + msg)) {
				$("#act").val("paybalance");
				$("#mycheckoutform").submit();
			}
		});
		$("#cmdDeposit").click(function(){
			$.post("checkout.php",{act:'deposit', newcash: $("#newcash").val(), newcard:$("#newcard").val(), 
				newchange: $("#newchange").val(), occupancy: $("#occupancy").val(), roomid: $("#roomid").val()},function(resp){
			});			
			alert('Deposit accepted.');
			$("#mycheckoutform").submit();
		});
		$('#cmdNorefund').click(function(){
			$('#newcash').val(0);
			$('#new_balance').val(0);
			$('#norefundflag').val(1);
			$('#cmdCheckout').show();
		});
		
		//$("#cmdPrintSOA").click(function(){
		//	$.post("soa.php?roomid=<?=$room?>&print=2");
		//});
		$("#cmdCheckout").click(function(){
			$("#act").val("checkout");			
			$("#mycheckoutform").submit();
		});
		$("#cmdAccept").click(function(){
			$("#act").val("security");
			$("#mycheckoutform").submit();
		});
		$("#new_adj_pwd").keypad();
		$("#cashvalue").keypad();
		$("#minibar_item_count").keypad();
		$("#addminibar").attr("disabled", ($("#minibar_item_count").val()==0));
		$("#minibar_item_count").change(function(){
			$("#addminibar").attr("disabled", ($("#minibar_item_count").val()==0));
		});

		$("#cmdFingerScan").click(function(){
			$.post("oicfscan.php",{act:'scan', user: $("#new_adj_oic").val()});
			myinterval = setInterval(checkFScan, 3000);
		});
		$("#cmdFingerScan2").click(function(){
			$.post("oicfscan.php",{act:'scan', user: $("#new_adj_oic2").val()});
			myinterval = setInterval(checkFScan2, 3000);
		});
});
function checkFScan(){
	$.post("oicfscan.php",{act:'monitor', user: $("#new_adj_oic").val()},
	function(resp){
		if(resp.success==true) {
			$("#new_adj_pwd").val(resp.pass);
			$("#cmdApprove").trigger("click");
			clearInterval(myinterval);
		}
	},'json');
}
function checkFScan2(){
	$.post("oicfscan.php",{act:'monitor', user: $("#new_adj_oic2").val()},
	function(resp){
		if(resp.success==true) {
			$("#new_adj_pwd2").val(resp.pass);
			$("#cmdApprove2").trigger("click");
			clearInterval(myinterval);
		}
	},'json');
}
</script>

<form name='mycheckouform'  id="mycheckoutform" method='post'>
<input type="hidden" name="roomid"  id="roomid" value="<?=$room?>" />
<input type="hidden" name="occupancy"  id="occupancy" value="<?=$obj->occupancy?>" />
<input type="hidden" name="act"  id="act" value="" />
<table width='600'>
<tr><td valign="top">

<fieldset style="width:300px"><legend>Adjustments/Deduction</legend>
<table id="adjustmenttable">
<tr>
<td>Category</td>
<td>
<select name='newsalestype' id='newsalestype'>
<option value=''></option>
<option value='room'>Room </option>
<option value='misc'>Miscellaneous</option>
<option value='food'>Food and Beverages</option>
<option value='beer'>Beer</option>
</select>
</td>
</tr>
<tr>
<td>Action</td>
<td><input type="radio" name="rbltype" id="rbltype_1" value="Adjustment" checked><label for="rbltype_1">Adjustment</label>
<br><input type="radio" name="rbltype" id="rbltype_2" value="Cancellation"><label for="rbltype_2">Deduction/Cancellation</label>
</td>
</tr>
<tr>
<td>Reason</td>
<td><div id="divAdjustment">
<?php
echo $obj->getdropdownremarks(4);
?>
</div>
<div id="divCancel">
<?php
echo $obj->getdropdownremarks(2);
?>
</div>
</td>
</tr>
<tr>
<td>Amount</td>
<td><input type="text" name="new_adjustment" id="new_adjustment" class="adjustelement" /></td>
</tr>
<tr>
<td valign="top">Supervisor/OIC:</td>
<td>
Username:<br>
<?php
$sql = "select username, fullname from users where group_id=4";
$res = mysql_query($sql);
echo "<select name='new_adj_oic' id='new_adj_oic'>";
echo "<option ></option>";
while(list($usr,$full)=mysql_fetch_row($res))
{
	echo "<option value='$usr'>$full</option>";
}
echo "</select>";

?>
<input type="button" name="cmdFingerScan" id="cmdFingerScan" value="Finger Scan" /><br>
Password:<br>
<input type="password" name="new_adj_pwd" id="new_adj_pwd"  />
<input type="button" value="Approve" name="cmdApprove" id="cmdApprove" />
</td>
</tr>
</table>


</fieldset>


<fieldset style="width:300px">
<legend>Receivables</legend>

 <div class='error'>
<?php 
if(isset($_GET['recerr'])) echo $_GET['recerr'];
 ?> 
 </div>
<table id="securitytable">
<tr>
<td>
<select name='receivable_type' id='receivable_type'>
<option value='Security Deposit'>Security Deposit</option>
<option value='Management Endorsement'>Management Endorsement</option>
</select>
</td>
</tr>
<tr>
<td colspan=2>
Guest Name:<br />
<input type="text" name="recvbl_firstname" id="recvbl_firstname" />
<input type="text" name="recvbl_lastname" id="recvbl_lastname"/>
</td>
</tr>
<tr>
<td >Remarks<br />
<textarea cols=30 rows=1 name='recvbl_remarks' id='recvbl_remarks'></textarea></td>
</tr>
<tr>
<td >
Cash Value:
<input type="text" name="recvbl_cashvalue" id="recvbl_cashvalue" />
<!-- <input type="button" name="cmdAccept2" value="Accept" id="cmdAccept2" class="cmdbtn" /> -->
</td>
</tr>
<tr>
<td valign="top">Supervisor/OIC:</td>
</tr>
<tr>
<td>
Username:<br>
<?php
$sql = "select username, fullname from users where group_id=4";
$res = mysql_query($sql);
echo "<select name='new_adj_oic2' id='new_adj_oic2'>";
echo "<option ></option>";
while(list($usr,$full)=mysql_fetch_row($res))
{
	echo "<option value='$usr'>$full</option>";
}
echo "</select>";

?>
<input type="button" name="cmdFingerScan2" id="cmdFingerScan2" value="Finger Scan" /><br>
Password:<br>
<input type="password" name="new_adj_pwd2" id="new_adj_pwd2"  />
<input type="button" value="Approve" name="cmdApprove2" id="cmdApprove2" />
</td>
</tr>
</table>

</fieldset>

<fieldset id="minibar">
<legend>Minibar</legend>
<table class="formtable">
<tr>
<td>
<?php
$sql =" select a.minibar_id,a.fnb_id, a.amount,b.fnb_name from minibar a, fnb b where a.fnb_id=b.fnb_id ";
$res = mysql_query($sql);
$minibar = "<select name='minibar_item' id='minibar_item'>";
$barlist="<table class='formtable'>";
$barlist.="<tr><th colspan=2>Minibar Contents on Checkin</th></tr>";
$barlist.="<tr><th>Item</th><th>Qty</th></tr>";
while(list($mbid, $fnbid, $amount,$fnbname)=mysql_fetch_row($res)) {

	$qty=getRoomMinibarQty($_GET["roomid"],$mbid);
	$barlist.= "<tr>";
	$barlist.= "<td>$fnbname</td>";
	$barlist.= "<td>$qty</td>";
	$barlist.= "</tr>";
	$minibar.="<option value='$fnbid'>$fnbname</option>";
}
$minibar .= "</select>";
$barlist.="</table>";
echo $minibar;
?>
</td>
<td>
<input type='text' name='minibar_item_count' id='minibar_item_count' value='0' size='3' />
<input type='submit' name='addminibar' value='Add' id="addminibar" onclick='$("#act").val("addminibar")' />
</td> 
</table>
<?php echo $barlist; ?>
</fieldset>

<!---------split here--------->


</td><td>&nbsp;</td>
<td valign='top'  align='right'>
<fieldset style="width:300px"><legend>Balances</legend>
<table id="balancetable">
<?php
//adjustments here
//check for overtime
$rm->getovertimehours();

if($rm->overtime_hours >= 1) {
	$add_cost = $rm->ot_amount * $rm->overtime_hours;
	//echo $rm->ot_amount."xxx";
	$add_cost_f = number_format($add_cost,2);
	echo "<tr><td colspan=2><div>{$rm->overtime_hours} Hours Overtime Cost:<span style='float:right'>$add_cost_f</span></div></td></tr>";
}

?>
<tr>
<td colspan="2">
<?=$obj->getCheckoutFnbBalance() ?>
</td>
</tr>
<tr>
<td colspan="2">
<?=$obj->getCheckoutMOSBalance() ?>
</td>
</tr>
<tr>
<td colspan="2">
<?=$obj->getCheckoutRoomBalance() ?>
</td>
</tr>
<tr>
<td><span class="balance">Running Balance:</span></td>
<td>
<input type="text" class="balance" name="new_balance" id="new_balance" value="<?=number_format($obj->totalbalance + $add_cost,2)?>" />
<input type="hidden" name="hiddentotal" id="hiddentotal" value="<?=$obj->totalbalance + $add_cost?>" />
<input type="hidden" name="hiddenotamount" id="hiddenotamount" value="<?=$rm->ot_amount?>" />
<input type="hidden" name="hiddenothours" id="hiddenothours" value="<?=$rm->overtime_hours?>" />
</td>
</tr>
</table>

<input type="button" id="cmdPay" value="Transact" style="width:100%" /><br /><br />
<input type="button" id="cmdDeposit" value="Accept Deposit" style="width:100%" /><br /><br />
<input type="button" id="cmdNorefund" value="No Refund" style="width:100%" />
<input type="hidden" id="norefundflag"  name="norefundflag" value="0" />
<br><br>
<!--input type="button" id="cmdPrintSOA" value="Print Final SOA" style="width:100%" /><br><br-->
<?php if( in_array($_SESSION['hotel']['groupid'], array(1,5) ) ) : ?>

<input type="button" id="cmdCheckout" value="Checkout" style="width:100%" />
<?php endif; ?>
<div style='float:left'  id="receiptflagdiv">
<input type='checkbox' id='receiptflag' name='receiptflag' checked=true /><label for='receiptflag' style='font-size:10px'>Receipt Requested</label>
</div>
</fieldset>

<fieldset style="width:300px">
<legend>Payment / Deposit</legend>
<?=displaypaymentpad($obj->totalbalance + $add_cost)?>
</fieldset>


</td></tr>
</table>
</form>


